import { getLoginUserUsingGet, updateMyUserUsingPost } from '@/services/znxs-bi/userController';
import { ProCard, ProForm, ProFormText } from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { Button, Col, Image, message, Row } from 'antd';
import { useEffect, useState } from 'react';

const Center: React.FC = () => {
  // 获取系统用户

  // 用户修改提交对象
  const [userInfo, setUserInfo] = useState<API.UserVO>();

  // 使用effect 获取用户信息
  useEffect(() => {
    // 组件加载的时候获取用户信息
    const fetchUserInfo = async () => {
      try {
        const data = await getLoginUserUsingGet();
        setUserInfo(data.data);
      } catch (error) {
        console.error('获取用户信息失败:', error);
        setUserInfo({});
      }
    };
    // 调用获取用户信息
    fetchUserInfo();
  }, []); // 空依赖数组确保只在组件挂载时运行一次

  return (
    <>
      <div>
        <Row gutter={24}>
          <Col span={12}>
            <div
              style={{
                maxWidth: 400,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
              }}
            >
              <Image src={userInfo?.userAvatar} style={{ maxWidth: 200 }}></Image>
            </div>

            <ProCard
              title={userInfo?.userName}
              headStyle={{ color: 'red' }}
              bordered
              style={{ maxWidth: 400, userSelect: 'none' }}
            >
              {userInfo?.userProfile}
            </ProCard>
          </Col>
          <Col span={12}>
            <ProForm<API.UserVO>
              onFinish={async (values) => {
                // 提交表单，获取数据
                if (values) {
                  const res = await updateMyUserUsingPost(values);
                  if (res.code === 200) {
                    message.success('修改成功');
                    history.push('/');
                  } else {
                    message.error('修改失败' + res.message);
                    // 刷新当前页面
                    location.reload();
                  }
                }
              }}
              submitter={{
                render: (props, doms) => {
                  return [
                    ...doms,
                    <Button
                      key="back-to-home"
                      ghost
                      type="primary"
                      onClick={() => {
                        history.push('/');
                      }}
                    >
                      返回主页
                    </Button>,
                  ];
                },
              }}
              style={{ userSelect: 'none', maxWidth: 400 }}
            >
              <ProFormText name="userName" label="姓名" />
              <ProFormText name="userAvatar" label="头像地址" />
              <ProFormText name="userProfile" label="简介" />
            </ProForm>
          </Col>
        </Row>
      </div>
    </>
  );
};

export default Center;
